package com.lbh.cloudgallery.service.impl;

import com.lbh.cloudgallery.entity.ProductEntity;
import com.lbh.cloudgallery.entity.vo.OrderItemVos;
import com.lbh.cloudgallery.service.OrderService;
import com.lbh.cloudgallery.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.common.utils.PageUtils;
import com.xxx.common.utils.Query;

import com.lbh.cloudgallery.dao.CartItemDao;
import com.lbh.cloudgallery.entity.CartItemEntity;
import com.lbh.cloudgallery.service.CartItemService;


@Service("cartItemService")
public class CartItemServiceImpl extends ServiceImpl<CartItemDao, CartItemEntity> implements CartItemService {

    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService orderService;
    private  OrderItemVos vo;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CartItemEntity> page = this.page(
                new Query<CartItemEntity>().getPage(params),
                new QueryWrapper<CartItemEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CartItemEntity> getByCartId(Long cartId) {

        List<CartItemEntity> list = baseMapper.selectList(new QueryWrapper<CartItemEntity>().eq("cart_id", cartId));
        return list;
    }

    @Override
    public String createFromCart(Long memberId, Integer productId, Integer count) {

        ProductEntity ware = productService.getById(productId);
        if (ware != null) {
            Long stock = ware.getWare();
            if (stock > count) {
                //库存充足，加入订单
                //1.删除购物车
                this.remove(new QueryWrapper<CartItemEntity>().eq("member_id", memberId).eq("product_id", productId));
                //2.删除库存
                productService.deleteStock(productId, count);

                return "库存充足";
            } else return ware.getName() + "现库存不足，请择日购买。";
        } else {
            return "库存不足，请择日购买。";
        }
    }

    @Override
    public String deleteCartItem(Long memberId, Integer productId) {

        boolean b = this.remove(new QueryWrapper<CartItemEntity>()
                .eq("member_id", memberId).eq("product_id", productId));
        if (b){
            return "移除成功";
        }else return "移除失败";
    }


}